package mx.com.switz.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import mx.com.switz.dao.UsuarioDao;
import mx.com.switz.dto.Usuario;
public class CustomUserDetailsService  implements UserDetailsService{

	@Autowired
	private UsuarioDao usuarioDao;
	@Override
	public UserDetails loadUserByUsername(String nombre)
			throws UsernameNotFoundException {
		
		// Declare a null Spring User
				UserDetails user = null;
		// TODO Auto-generated method stub
				
				try {
					
					// Search database for a user that matches the specified username
					// You can provide a custom DAO to access your persistence layer
					// Or use JDBC to access your database
					// DbUser is our custom domain user. This is not the same as Spring's User
					Usuario u=usuarioDao.selectUsuario(nombre).get(0);
					System.out.println("u  "+u.getNombre());
					
					// Populate the Spring User object with details from the dbUser
					// Here we just pass the username, password, and access level
					// getAuthorities() will translate the access level to the correct role type

					user =  new User(
							u.getNombre(), 
							u.getPassword().toLowerCase(),
							true,
							true,
							true,
							true,
							getAuthorities(u.getRol()) );

				} catch (Exception e) {
					
					throw new UsernameNotFoundException("Error in retrieving user");
				}
				
				// Return user to Spring for processing.
				// Take note we're not the one evaluating whether this user is authenticated or valid
				// We just merely retrieve a user that matches the specified username
				return user;
		
	}
	
	
	 public Collection<GrantedAuthority> getAuthorities(Integer access) {
			// Create a list of grants for this user
			List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
			
		
		
			if ( access.compareTo(1) == 0) {
				// User has admin access
				
				authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
			}
			else if ( access.compareTo(0) == 0) {
				
				
				authList.add(new GrantedAuthorityImpl("ROLE_USER"));
			}

			// Return list of granted authorities
			return authList;
	  }

}
